package com.smart.community.gateway.config;

import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import reactor.core.publisher.Mono;

/**
 * 网关限流配置
 * 
 * @author Wu.Liang
 * @since 2024-12-21
 */
@Configuration
public class RateLimiterConfig {
    
    /**
     * IP地址限流解析器（主要限流策略）
     * 
     * @return IP地址限流解析器
     */
    @Bean
    @Primary
    public KeyResolver ipKeyResolver() {
        return exchange -> {
            String ip = exchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
            return Mono.just(ip);
        };
    }
    
    /**
     * 用户ID限流解析器
     * 
     * @return 用户ID限流解析器
     */
    @Bean("userKeyResolver")
    public KeyResolver userKeyResolver() {
        return exchange -> {
            String userId = exchange.getRequest().getHeaders().getFirst("X-User-Id");
            if (userId == null) {
                // 从请求头中获取用户ID，如果没有则使用IP
                String ip = exchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
                return Mono.just("ip:" + ip);
            }
            return Mono.just("user:" + userId);
        };
    }
    
    /**
     * 路径限流解析器
     * 
     * @return 路径限流解析器
     */
    @Bean("pathKeyResolver")
    public KeyResolver pathKeyResolver() {
        return exchange -> {
            String path = exchange.getRequest().getPath().value();
            return Mono.just(path);
        };
    }
}
